const jwt = require('jsonwebtoken')
const { atguigu } = require('../config/config')

module.exports = (req, res, next) => {
  const token = req.get('token')
  if (!token) {
    res.json({
      code: '2003',
      msg: 'token缺失！',
      data: null,
    })
    return
  }
  jwt.verify(token, atguigu, (err, data) => {
    if (err) {
      res.json({
        code: '2004',
        msg: 'token无效！',
        data: null,
      })
      return
    }
    req.user = data // 把jwt中的内容存储到请求对象中
    next()
  })
}